﻿using AutoMapper;
using PowerHub.MES.DTO.BasicData.DTO;
using PowerHub.MES.DTO.BasicData.QueryDto;
using PowerHub.MES.EFBase;
using PowerHub.MES.Entities.BasicData;
using PowerHub.MES.Entities;
using PowerHub.MES.IRepository.IBasic;
using PowerHub.MES.IServices.IBasic;
using PowerHub.MES.Jwt;
using PowerHub.MES.ReturnEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PowerHub.MES.IServices.IShopfloor;
using PowerHub.MES.Entities.Shopfloor;
using PowerHub.MES.DTO.Shopfloor.QueryDTO;
using PowerHub.MES.DTO.Shopfloor.DTO;
using PowerHub.MES.IRepository.IShopfloor;
using PowerHub.MES.Common.NumberingCenter;

namespace PowerHub.MES.Services.Shopfloor
{
    /// <summary>
    /// 工作站接口实现层
    /// </summary>
    public class Shopfloor_WorkStationServices : BaseServices<Shopfloor_WorkStation>, IShopfloor_WorkStationServices
    {
        private IShopfloor_WorkStationRepository _iShopfloor_WorkStationRepository;
        public UserServices _userServices;
        private IMapper _mapper;
        private static Random random = new Random();

        public Shopfloor_WorkStationServices(PowerHubMesContext powerHubMesContext, IShopfloor_WorkStationRepository iShopfloor_WorkStationRepository, UserServices userServices, IMapper mapper) : base(powerHubMesContext)
        {
            _iShopfloor_WorkStationRepository = iShopfloor_WorkStationRepository;
            _userServices = userServices;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取工作站列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationPageResult<List<Shopfloor_WorkStation>>> GetShopfloor_WorkStationPageListAsync(QueryShopfloor_WorkStationDTO query)
        {
            var ss = _userServices.UserId;
            var UserName = _userServices.UserName;
            var Role = _userServices.Role;
            return await _iShopfloor_WorkStationRepository.GetShopfloor_WorkStationPageListAsync(query);
        }

        /// <summary>
        /// 添加工作站
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> CreateShopfloor_WorkStationAsync(Shopfloor_WorkStationDTO query)
        {
            Shopfloor_WorkStation WorkStation = await GetEntityAsync(d => d.WorkStationName.Equals(query.WorkStationName)&& d.IsDel==0);
            if (WorkStation!=null)
            {
                throw new Exception("你输入的工作站名称已存在！");
            }
            if (string.IsNullOrEmpty(query.EquipmentManagementId))
            {
                throw new Exception("请选择设备信息");
            }
            if (string.IsNullOrEmpty(query.ProcessId))
            {
                throw new Exception("请选择工序信息");
            }
            if (string.IsNullOrEmpty(query.ProductionLineId))
            {
                throw new Exception("请选择产线信息");
            }
            var WorkStationEquipmentManagement = await GetEntityAsync(g => g.EquipmentManagementId.Equals(query.EquipmentManagementId) && g.IsDel == 0);
            if (WorkStationEquipmentManagement!=null)
            {
                throw new Exception("当前设备已绑定其它站台");
            }

            //实体转换
            var Shopfloor_WorkStation = _mapper.Map<Shopfloor_WorkStation>(query);
            Shopfloor_WorkStation.Id = Guid.NewGuid().ToString();
            Shopfloor_WorkStation.WorkStationNo = string.IsNullOrEmpty(query.WorkStationNo) || query.WorkStationNo.Contains(" ") ? GenerateBasicDataNO.GenerateCode(query.WorkStationName) : query.WorkStationNo;
            Shopfloor_WorkStation.Creator = _userServices.UserName;

            return await _iShopfloor_WorkStationRepository.CreateShopfloor_WorkStationAsync(Shopfloor_WorkStation);
        }


        /// <summary>
        /// 生成编号
        /// </summary>
        /// <param name="customCode"></param>
        /// <param name="sequenceLength"></param>
        /// <returns></returns>
        public string GetWorkStationNO(string customCode = "56", int sequenceLength = 5)
        {
            Shopfloor_WorkStation shopfloor_WorkStation = GetEntityListAsync(u => u.IsDel == 0).Result.OrderByDescending(u => u.WorkStationNo).FirstOrDefault();

            int sequenceNumber = 0;
            if (shopfloor_WorkStation != null)
            {
                string JobNumber = shopfloor_WorkStation.WorkStationNo.Substring(shopfloor_WorkStation.WorkStationNo.Length - 5);
                sequenceNumber = Convert.ToInt32(JobNumber);
            }
          
            // 获取当前年份的简写（只取后两位）  
            string yearShort = DateTime.Now.Year.ToString().Substring(2, 2);
            sequenceNumber++;
            string sequence = sequenceNumber.ToString().PadLeft(sequenceLength, '0');

            return yearShort + customCode + sequence;
        }

        /// <summary>
        /// 批量删除工作站
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> DeletionShopfloor_WorkStationAsync(List<string>? ids)
        {
            if (ids.Count < 1)
            {
                throw new Exception("请先选择数据！");
            }
            return await _iShopfloor_WorkStationRepository.DeletionShopfloor_WorkStationAsync(ids);
        }


        /// <summary>
        /// 更新工作站
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<OperationResult<bool>> UpdateShopfloor_WorkStationAsync(Shopfloor_WorkStationDTO query)
        {
            if (query == null)
            {
                throw new Exception("请先选择数据！");
            }
            var WorkStationEquipmentManagement = await GetEntityAsync(g => g.EquipmentManagementId.Equals(query.EquipmentManagementId) && g.IsDel==0 && g.Id!= query.Id);
            if (WorkStationEquipmentManagement != null)
            {
                throw new Exception("当前设备已绑定其它站台");
            }

            //根据id获取工作站信息
            Shopfloor_WorkStation Shopfloor_WorkStation = await GetEntityAsync(d => d.Id.Equals(query.Id));
            if (Shopfloor_WorkStation == null)
            {
                throw new Exception("更新工作站信息发生了异常,请刷新页面后试试");
            }
            Shopfloor_WorkStation.EquipmentManagementId = query.EquipmentManagementId;
            Shopfloor_WorkStation.WorkStationName = query.WorkStationName;
            Shopfloor_WorkStation.ProductionLineId = query.ProductionLineId;
            Shopfloor_WorkStation.ProcessId = query.ProcessId;
            Shopfloor_WorkStation.Updator = _userServices.UserName;


            return await _iShopfloor_WorkStationRepository.UpdateShopfloor_WorkStationAsync(Shopfloor_WorkStation);

        }
    }
}
